package org.csu.mybigpro.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage; // 导入 IPage
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.csu.mybigpro.DTO.ClassroomBookingDTO;
import org.csu.mybigpro.DTO.ClassroomDTO;
import org.csu.mybigpro.domain.Classroom;
import org.csu.mybigpro.domain.ClassroomBooking;
import org.csu.mybigpro.domain.User;
import org.csu.mybigpro.persistence.ClassroomBookingMapper;
import org.csu.mybigpro.persistence.ClassroomMapper;
import org.csu.mybigpro.persistence.UserMapper;
import org.csu.mybigpro.service.ClassroomBookingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ClassroomBookingServiceImpl extends ServiceImpl<ClassroomBookingMapper, ClassroomBooking> implements ClassroomBookingService {

    @Autowired
    private ClassroomBookingMapper bookingMapper; // MyBatis-Plus的Mapper

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ClassroomMapper classroomMapper;

    @Override
    public List<ClassroomBookingDTO> getAllReviewedWithNames() {
        return bookingMapper.selectReviewedWithTeacherAndClassroom();
    }

    @Override
    public List<ClassroomBookingDTO> getBookingsByTeacherName(String teacherName) {
        // 先根据教师名字模糊查询用户id列表
        List<User> users = userMapper.selectList(
                new QueryWrapper<User>().like("name", teacherName)
        );
        if (users.isEmpty()) {
            return Collections.emptyList();
        }

        List<Long> teacherIds = users.stream().map(User::getId).collect(Collectors.toList());

        // 查询借用记录
        List<ClassroomBooking> bookings = bookingMapper.selectList(
                new QueryWrapper<ClassroomBooking>().in("teacher_id", teacherIds)
        );

        return bookings.stream().map(booking -> {
            ClassroomBookingDTO dto = new ClassroomBookingDTO();
            dto.setId(booking.getId());
            dto.setStatus(booking.getStatus());
            dto.setApplyTime(booking.getApplyTime());
            dto.setReviewTime(booking.getReviewTime());
            dto.setRemark(booking.getRemark());

            // 设置教师名
            User user = userMapper.selectById(booking.getTeacherId());
            dto.setTeacherName(user != null ? user.getName() : null);

            // 设置教室编号
            Classroom classroom = classroomMapper.selectById(booking.getClassroomId());
            dto.setClassroomNumber(classroom != null ? classroom.getRoomNumber() : null);

            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public List<ClassroomBookingDTO> getBookingsByRoomNumber(String roomNumber) {
        // 1. 模糊查询教室编号匹配的教室列表
        List<Classroom> classrooms = classroomMapper.selectList(
                new QueryWrapper<Classroom>().like("room_number", roomNumber)
        );
        if (classrooms == null || classrooms.isEmpty()) {
            return Collections.emptyList();
        }

        // 2. 提取所有匹配教室的ID
        List<Long> classroomIds = classrooms.stream()
                .map(Classroom::getId)
                .collect(Collectors.toList());

        // 3. 查询所有对应的借用记录
        List<ClassroomBooking> bookings = bookingMapper.selectList(
                new QueryWrapper<ClassroomBooking>().in("classroom_id", classroomIds)
        );

        // 4. 封装DTO返回
        return bookings.stream().map(booking -> {
            ClassroomBookingDTO dto = new ClassroomBookingDTO();
            dto.setId(booking.getId());
            dto.setStatus(booking.getStatus());
            dto.setApplyTime(booking.getApplyTime());
            dto.setReviewTime(booking.getReviewTime());
            dto.setRemark(booking.getRemark());

            // 教师姓名
            User user = userMapper.selectById(booking.getTeacherId());
            dto.setTeacherName(user != null ? user.getName() : null);

            // 教室编号（根据 classroom_id 获取）
            Classroom matchedClassroom = classrooms.stream()
                    .filter(c -> c.getId().equals(booking.getClassroomId()))
                    .findFirst()
                    .orElse(null);
            dto.setClassroomNumber(matchedClassroom != null ? matchedClassroom.getRoomNumber() : null);

            return dto;
        }).collect(Collectors.toList());
    }
    @Override
    public List<ClassroomDTO> getAllClassroomsWithBookingStatus(LocalDate date) {
        // 获取所有教室
        List<Classroom> allClassrooms = classroomMapper.selectList(null);

        // 获取当天所有已批准的借用记录
        // 这里的逻辑是：如果一个借用的结束时间 >= 查询日期的开始，并且开始时间 <= 查询日期的结束，则认为当天有冲突
        QueryWrapper<ClassroomBooking> bookingQueryWrapper = new QueryWrapper<>();
        bookingQueryWrapper.eq("status", 1) // 只考虑已批准 (status = 1) 的借用
                .ge("end_time", date.atStartOfDay()) // 结束时间晚于或等于查询日期的开始
                .le("start_time", date.plusDays(1).atStartOfDay().minusNanos(1)); // 开始时间早于或等于查询日期的结束（确保不跨越到下一天的开始）

        List<ClassroomBooking> bookedClassroomsToday = bookingMapper.selectList(bookingQueryWrapper);

        // 将已借用的教室ID集合化，方便查找
        List<Long> bookedClassroomIds = bookedClassroomsToday.stream()
                .map(ClassroomBooking::getClassroomId)
                .distinct()
                .collect(Collectors.toList());

        // 封装成 ClassroomDTO
        return allClassrooms.stream().map(classroom -> {
            ClassroomDTO dto = new ClassroomDTO();
            dto.setId(classroom.getId());
            dto.setRoomNumber(classroom.getRoomNumber());
            dto.setLocation(classroom.getLocation());
            dto.setCapacity(classroom.getCapacity()); // 假设 Classroom 实体有 capacity 字段
            dto.setStatus(bookedClassroomIds.contains(classroom.getId())); // 判断当天是否被借用
            return dto;
        }).collect(Collectors.toList());
    }


}
